package com.ruoyi.common.filter

import com.ruoyi.common.enums.HttpMethod
import com.ruoyi.common.utils.StringUtils
import com.ruoyi.common.utils.StringUtils.isNotEmpty
import java.io.IOException
import java.util.*
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 防止XSS攻击的过滤器
 *
 * @author ruoyi
 */
class XssFilter : Filter {
    /**
     * 排除链接
     */
    private var excludes: MutableList<String?> = ArrayList()

    @Throws(ServletException::class)
    override fun init(filterConfig: FilterConfig) {
        val tempExcludes = filterConfig.getInitParameter("excludes")
        if (isNotEmpty(tempExcludes)) {
            val url = tempExcludes.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            Collections.addAll(excludes, *url)
        }
    }

    @Throws(IOException::class, ServletException::class)
    override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
        val req = request as HttpServletRequest
        val resp = response as HttpServletResponse
        if (handleExcludeURL(req, resp)) {
            chain.doFilter(request, response)
            return
        }
        val xssRequest = XssHttpServletRequestWrapper(request)
        chain.doFilter(xssRequest, response)
    }

    private fun handleExcludeURL(request: HttpServletRequest, response: HttpServletResponse): Boolean {
        val url = request.servletPath
        val method = request.method
        // GET DELETE 不过滤
        return if (method == null || HttpMethod.GET.matches(method) || HttpMethod.DELETE.matches(method)) {
            true
        } else StringUtils.matches(url, excludes)
    }

    override fun destroy() {}
}
